package controller;

import java.util.List;

import model.Bar;
import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;



import dao.BarDAO;

@Resource
public class BarController {
	
	private final BarDAO barDAO;
	private final Result result;
	private final Validator validator;
	
	public BarController(BarDAO barDAO, Result result, Validator validator){
		this.barDAO = barDAO;
		this.result = result;
		this.validator = validator;
	}

	@Post @Path("/bars")
	public void save(Bar bar){
		
		this.validateData(bar);
		
		this.barDAO.save(bar);
		(this.result.redirectTo(this)).bars();
	}

	@Put @Path("/bars/{bar.id}")
	public void update(Bar bar){
		
		this.validateData(bar);
		
		this.barDAO.update(bar);
		(this.result.redirectTo(this)).bars();
	}

	@Get @Path("/bars")
	public List<Bar> bars(){
		return this.barDAO.list();
	}

	@Get @Path("/bars/{id}")
	public Bar retrieve(Long id){
		return this.barDAO.retrieve(id);
	}

	@Delete @Path("/bars/{id}")
	public void remove(Long id){
		Bar bar = this.barDAO.retrieve(id);
		this.barDAO.remove(bar);
		(this.result.forwardTo(this)).bars();
	}

	@Get @Path("/bars/new")
	public void formulario(){
		
	}
	
	private void validateData(final Bar bar){
		if(bar.getQuality() < 1 || bar.getQuality() > 5) {
			validator.add(new ValidationMessage("Qualidade deve estar entre 1 e 5.", "quality.out_of_range"));
		}
		validator.onErrorUsePageOf(BarController.class).formulario();
	}
	
}
